<?php
  /**
   *  Cria um select a partir do resultado de uma consulta em um db_Table.
   *  Extends http://www.ricardosimoes.com/cms/index.php?option=com_content&amp;view=article&amp;id=84:estendendo-zendformelement&amp;catid=3:-programa-e-desenvolvimento-web&amp;Itemid=4
   */
class Arm_Form_Element_DbSelect extends Zend_Form_Element_Select
{
    ### Model da entidade referenciada
    private $_model             = '';
    private $_identityColumn    = 'id';
    private $_valueColumn       = 'name';
    private $_condition         = null;
    private $_select            = null;
    
    public function init(){
        parent::init();
    }
    
    public function setModel($model){
        $this->_model           = $model;
    }
    
    public function setIdentityColumn($identityColumn){
        $this->_identityColumn  = $identityColumn;
    }
    
    public function setValueColumn($valueColumn){
        $this->_valueColumn     = $valueColumn;
    }
    
    public function setCondition($condition){
        $this->_condition       = $condition;
    }
    
    public function setSelect($select){
        $this->_select          = $select;
    }
    
    public function render(Zend_View_Interface $view  = null){
        $this->_performSelect();
        return parent::render($view);
    }
    
    ## Realiza a consulta de acordo com os valores setados (ou os valores default)
    ## e a partir do resultado, constroi o select
    private function _performSelect(){
        $model          = new $this->_model;
        
        if(!is_null($this->_select)){
            $select = $this->_select;
        }
        else{
            $select         = $model->select();
            
            if(!is_null($this->_condition)){
                $select     ->where($this->_condition);
            }
            
            $select     ->order("{$this->_valueColumn} ASC");
        }
        
        $results        = $model->fetchAll($select);
        
        $options[null]  = "";
        foreach($results as $item){
            $array  = $item->toArray();
            
            if(!is_null($this->_valueColumn)){
                $options[$array[$this->_identityColumn]]    = $array[$this->_valueColumn];
            }
            else{
                $options[$array[$this->_identityColumn]]    = $item->__toString();
            }
        }
        
        $this->setMultiOptions($options);
    }
}
